package com.zk.mockito.cases;

import org.junit.Test;
import org.mockito.MockedConstruction;

import java.util.List;

import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.*;

/**
 * Mock 构造器
 */
public class Case016_MockedConstruction {

    class Foo {
        public String method() {
            return "foo";
        }
    }

    /**
     *  调用constructed
     */
    @Test
    public void testMockedConstructionConstructed() {

        assertEquals("foo", new Foo().method());
        try (MockedConstruction<Foo> mocked = mockConstruction(Foo.class)) {
            // 可以使用constructed 获取实例，不需要手动new
            List<Foo> ctors = mocked.constructed();
            if (!ctors.isEmpty()) {
                Foo c = ctors.get(0);
                System.out.println(c.method());
            }
        }
        assertEquals("foo", new Foo().method());

    }

    /**
     *
     */
    @Test
    public void testMockedConstructionNewType() {

        assertEquals("foo", new Foo().method());
        try (MockedConstruction<Foo> mocked = mockConstruction(Foo.class)) {
            // 也可以手动new
            Foo foo = new Foo();
            when(foo.method()).thenReturn("bar");
            assertEquals("bar", foo.method());
            verify(foo).method();
        }
        assertEquals("foo", new Foo().method());

    }
}
